import 'dart:convert';
import 'package:http/http.dart' as http;
import '../models/chat_message.dart';

class SiliconApiService {
  final String apiKey;
  final String baseUrl = 'https://api.siliconflow.cn/v1/chat/completions';
  final String model;

  SiliconApiService({required this.apiKey, required this.model});

  Stream<String> sendMessageStream(
    String message, {
    List<ChatMessage> chatHistory = const [],
  }) async* {
    final List<Map<String, String>> messages = [];
    
    // 添加历史消息到上下文
    for (var msg in chatHistory) {
      messages.add({
        'role': msg.isUser ? 'user' : 'assistant',
        'content': msg.content,
      });
    }
    
    // 添加当前消息
    messages.add({
      'role': 'user',
      'content': message,
    });

    final request = http.Request('POST', Uri.parse(baseUrl));
    request.headers.addAll({
      'Content-Type': 'application/json',
      'Authorization': 'Bearer $apiKey',
      'Accept': 'text/event-stream',
    });
    
    request.body = jsonEncode({
      'model': model,
      'messages': messages,
      'stream': true,
    });

    final streamedResponse = await http.Client().send(request);
    
    if (streamedResponse.statusCode != 200) {
      throw Exception('API请求失败: ${streamedResponse.statusCode}');
    }

    await for (var chunk in streamedResponse.stream.transform(utf8.decoder)) {
      for (var line in chunk.split('\n')) {
        if (line.startsWith('data: ')) {
          final data = line.substring(6).trim();
          if (data == '[DONE]') break;
          
          try {
            final json = jsonDecode(data);
            final content = json['choices'][0]['delta']['content'];
            if (content != null && content.isNotEmpty) {
              yield content;
            }
          } catch (e) {
            print('解析响应出错: $e');
          }
        }
      }
    }
  }
} 